<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      #box1,
      #box2,
      #box3 {
        width: 100px;
        height: 100px;
        background-color: blueviolet;

        position: absolute;
        left: 0;
      }
    </style>
  </head>

  <body>
    <div id="box1" style="background-color: red; top: 0px"></div>
    <div id="box2" style="background-color: green; top: 100px"></div>
    <div id="box3" style="background-color: yellow; top: 200px"></div>

    <script>
      function animate(
        element, //想让谁动
        target = { left: 300, top: 400, opacity: 0.5 }, //目标状态
        timeCost = 1000, //时间消耗
        callback = function () {
          console.log("动画结束");
        } //动画结束时干点啥（回调）
      ) {
        var timer = setInterval(function () {
          element.style.left =
            parseFloat(window.getComputedStyle(element).left) + 10 + "px";
          element.style.top =
            parseFloat(window.getComputedStyle(element).top) + 10 + "px";
        }, 40);

        /* 只要时间一到 */
        setTimeout(function () {
          // 清除动画定时器
          clearInterval(timer);

          // 动画结束时回调callback函数
          callback();
        }, timeCost);
      }
    </script>

    <script>
      [box1, box2, box3].forEach(function (item) {
        item.onclick = function () {
          animate(
            item, //想染谁动
            {}, //目标状态
            2000, //耗时
            // 动画结束回调函数
            function () {
              alert("动画结束了，快回家玩泥巴吧！");
            }
          );
        };
      });
    </script>
  </body>
</html>
